CS 211 Lesson 6
Branches
Quote:
Integrity is the fundamental premise for military service in a free society. Without integrity, the moral pillars of our military strength, public trust, and self-respect are lost. Charles A. Gabriel
Lesson Objectives:
Understand the purpose of branches
Know the syntax of the if construct
Be able to use one-, two-, and multiple-alternative if constructs
Be able to use nested if constructs
Know the syntax of the switch construct
Be able to use the switch construct
Understand the purpose of the try/catch construct
Lesson:
I. MATLAB Concepts
A. Control Structures
A control structure is a programming language mechanism for changing the order in which statements in a program are executed.
The most common control structures are branches (selection statements) and loops (repetition statements).
By default, statements are executed sequentially, from top to bottom.
A branch structure may cause execution to jump forward in a program, thus skipping over some code.
A loop structure may cause execution to jump backwards in a program, thus resulting in the same code being executed more than once.
For both branches and loops, the decision to jump forward or backwards typically is based on the result of a logical test.
MATLAB supports three types of branch statements: if, switch, and try/catch.
MATLAB supports two types of loop statements: while and for.
B. The if statement
MATLAB's if statement has several different forms which may be categorized as:
one-alternative if
two-alternative if
multiple-alternative if with else
multiple-alternative if without else
For a given problem, use the simplest form that will accomplish your task.
The one-alternative if has the following format (syntax):
if <logical expression>
<one or more statements>
end
For example:
if Body_temp > 98.6
fprintf('The patient has a fever.\n')
end
The one-alternative if statement behaves as follows:
If the logical expression evaluates to true, the statement(s) following the logical expression and before the end are executed. Otherwise (i.e., the logical expression evaluates to false), the statement(s) following the expression and before the end are not executed and execution skips to the statements following the end.
While not required, indenting the lines between the if and end lines is very important for readability
The two-alternative if has the following format (syntax):
if <logical expression>
<one or more statements>
else
<one or more statements>
end
For example:
if Body_temp > 98.6
fprintf('The patient has a fever.\n')
else
fprintf('The patient does not have a fever.\n');
end
The two-alternative if statement behaves as follows:
If the logical expression evaluates to true, the statement(s) following the logical expression and before the else are executed and execution skips to the statements following the end. Otherwise (i.e., the logical expression evaluates to false), the statement(s) before the else are skipped and the statements after the else and before the end are executed and execution continues with statements following the end.
With the two-alternative if, either the code before the else or the code after the else will always be executed (but never both).
Never put a logical expression immediately following the else. (MATLAB will ignore the expression if you include one.)
The multiple-alternative if with else has the following format (syntax):
if <logical expression>
<one or more statements>
elseif <logical expression>
<one or more statements>
<zero or more additional elseif blocks like the one above>
else
<one or more statements>
end
For example:
if Body_temp >= 102
fprintf('The patient has a high fever.\n')
elseif Body_temp >= 99
fprintf('The patient has a low grade fever.\n');
elseif Body_temp >= 96
fprintf('The patient has a normal body temperature.\n');
elseif Body_temp >= 92
fprintf('The patient has a low body temperature.\n');
else
fprintf('The patient is hypothermic.\n');
end
The multiple-alternative if with else behaves as follows:
The logical expressions are evaluated in order from top to bottom. The code immediately following the first logical expression that evaluates to true, if any do, is executed (up to the next elseif or the else) and then execution skips to the code following the end. If none of the logical expressions evaluate to true, the statements between the else and before the end are executed and execution continues with statements following the end.
One statement block always executes when using a multiple-alternative if with else statement.
Use a multiple-alternative if with else statement when your code should do something for all possible cases.
The multiple-alternative if without else has the following format (syntax):
if <logical expression>
<one or more statements>
elseif <logical expression>
<one or more statements>
<zero or more additional elseif blocks like the one above>
end
For example:
if Body_temp >= 102
fprintf('The patient has a high fever.\n')
elseif Body_temp > 98.6
fprintf('The patient has a low grade fever.\n');
elseif Body_temp < 95
fprintf('The patient has a low body temperature.\n');
end
The multiple-alternative if without else behaves as follows:
The logical expressions are evaluated in order from top to bottom. The code immediately following the first logical expression that evaluates to true is executed (up to the next elseif or the end) and then execution skips to the code following the end. If none of the logical expressions evaluate to true, none of the statement(s) are executed and execution resumes with statements following the end.
Either one statement block or no statement block will execute using a multiple-alternative if without else statement.
Use a multiple-alternative if without else statement when the code should take no action in at least one case.
if statements can be nested inside an if statement. For example:
if Body_temp >= 102
fprintf('The patient has a high fever.\n')
if Body_weight > 200 && Body_height < 64
fprintf('Send the patient to the hospital\n');
end
elseif Body_temp > 98.6
fprintf('The patient has a low grade fever.\n');
elseif Body_temp < 95
fprintf('The patient has a low body temperature.\n');
if Temperature_time > 90
fprintf('Send the patient to the hospital\n');
end
endDesign your if statements in such a way as to minimize logical tests.
Make sure your if statements do not include redundant tests. This makes your code more difficult to understand, harder to maintain over time, and slower to execute. The following is an example of a poorly-designed if statement with 4 unnecessary redundant tests.
if Score >= 90
disp('A')
elseif Score >= 80 & Score < 90
disp('B')
elseif Score >= 70 & Score < 80
disp('C')
elseif Score >= 60 & Score < 70
disp('D')
elseif Score < 60
disp('F')
endA better design without redundant tests is:
if Score >= 90
disp('A')
elseif Score >= 80
disp('B')
elseif Score >= 70
disp('C')
elseif Score >= 60
disp('D')
else
disp('F')
endThe key to avoiding redundant tests is to avoid testing for cases that have already been confirmed in earlier tests.
C. The switch statement
MATLAB's switch statement is a branch statement similar to a multiple-alternative if statement.
The switch statement has the following format (syntax):
switch (<switch expression>)
case {<case_expression_1>, <case_expression_2, ...}
<one or more statements>
<zero or more case blocks like the one above>
<otherwise,
<one or more statements> >
end
If there is only one case expression for a case block, the curly braces { } may be left off.
The final otherwise block is optional.
For example:
switch (Answer)
case {'y', 'Y'}
fprintf('Affirmative.\n')
case {'n', 'N'}
fprintf('Negative.\n')
case '?'
fprintf('Undecided.\n')
otherwise
fprintf('Invalid answer!\n')
end
The switch statement behaves as follows:
First, the switch expression is evaluated. Then the value of the switch expression is compared to the case expression values from the first case block to the last. If the value of the switch expression matches a case expression value, the statements in that case block are executed and then execution resumes with statements following the end. If none of the case expressions match the switch expression value and there is an otherwise block, the the code between the otherwise and the end is executed and execution continues with statements following the end.
Use a switch statement when you have a discrete number of choices (options) and they are all tests for equality.
D. The try/catch statement
The try/catch statement is an advanced branch statement used for exception handing.
The try/catch statement is useful to "catch" and recover from errors that occur when a program is executing.
The try/catch statement has the following format (syntax):
try
<one or more statements - error prone code>
catch
<one or more statements - error recovery code>
end
For example:
Vector = [2 4 6 8 10];
Index = input('Enter an index for the vector (1-5): ');
try
fprintf('The value at element %g is %g.\n', Index, Vector(Index))
catch
fprintf('ERROR - %g is not a valid index for the vector.\n', Index)
end
The try/catch statement behaves as follows:
The statement(s) after the try and before the catch are executed in sequence. If a run-time error occurs while executing any of these statement(s), the statement(s) following the catch and before the end are executed (instead of the program terminating as usual). If no error occurs, execution skips over the code between the catch and before the end.
For simple cases, a try/catch statement block can be written using normal if statements. For example:
Vector = [2 4 6 8 10];
Index = input('Enter an index for the vector (1-5): ');
if Index >= 1 && Index <= 5
fprintf('The value at element %g is %g.\n', Index, Vector(Index))
else
fprintf('ERROR - %g is not a valid index for the vector.\n', Index)
end
II. Good Programming Practices
Vertical alignment of statements makes program code easier to read and understand.
Vertically align, in the same column, corresponding if, else, elseif, and end keywords, indenting all statements inside them to the right at least 2 spaces
You can use MATLAB's smart indent feature (Text -> Smart Indent or Ctrl-I) to automatically indent selected code for you.
Maintaining proper indentation is essential for making
nested
control structures readable and understandable.
Multiple-alternative if
statements should test values in an orderly manner -- large cases to small
cases, or small cases to large cases.
Use a multiple-alternative if statement when you are dealing with floating point values that vary over a continuous range (e.g., Body_temperature)
Use a switch statement when you are dealing with a small range of discrete values (e.g., Class_letter_grade - 'A', 'B', 'C', 'D', or 'F')
III. Algorithms
(None for this lesson)
Lab Work: Lab 6
References: Chapman Textbook: section 3.4, branch_demos.m